//websocket定义
// var wxLogin = require("wxLogin");
var websocket = {
  
    ws: null,  //当前的webSocket的对象
    host: "ws://127.0.0.1:8088/game/admin1", //这里接口地址

    times: 20000, // 心跳检测频率5秒  
    heartBeatTimer: null, // 心跳定时器
    delayWaitTime: null,  // 延迟等待定时器
    lastReconnectTime: 0, // 最后一次向服务器发起重连延迟器
    resetCount:0, // 连续重连次数
    heartEvent:{ event: "heartBeat", data: "heartBeat" },
    HEARTBET: "heartBeat",
    WXLOGIN: "wxLogin",
    SYSLOGIN: "sysLogin",
    USERINFO: "userInfo",

    /**
     * 连接服务
     * @param {} res 
     * @returns 
     */
    connect(res) {
      console.log("服务器连接中···") 
        if (!this.ws) {
            this.ws = new WebSocket(this.host);
            this.ws.onopen = this._onOpen.bind(this);
            this.ws.onclose = this._onClose.bind(this);
            this.ws.onmessage = this._onMessage.bind(this);
            this.ws.onerror = this._onError.bind(this);
            console.log("websocket初始化完成！")
        }
        console.log(this.ws)
        return this.ws;
    },

    _onOpen(res) {
        this.ws.readyState === WebSocket.OPEN;

        // 当前环境为微信小游戏进行登录
        // if(cc.sys.platform == cc.sys.WECHAT_GAME){
        //   wxLogin.login()
        // }

        // 开始心跳
        this.heatCall();

        console.log("服务器连接成功！"+this.host);
    },

    _onClose(err) {
        this.ws = null 
        console.log("服务器连接已关闭！");        
    },


    /**
     * 消息处理
     * @param {} res 
     * @returns 
     */
    _onMessage(res) {
      console.log("收到服务器消息~");     
      // console.log(res)
      var data = JSON.parse(res.data);
      console.log(data)

      // 心跳消息
      if (data.event == this.HEARTBET) {
          console.log("服务器连接正常~")
          return;
      } 
      // 微信登录获取openId
      else if(data.event == this.WXLOGIN){
        console.log("微信认证返回")
        let openId = data.data.openid
        if (openId) {
          // wx.setStorageSync('openId', response.data.openid);
          this.sysAuthorize(openId)
        }
      }
      // 服务器认证登录
      else if(data.event == this.SYSLOGIN){
        console.log(data.data)
        let code = data.data.code;
        if (code === 200) {
          console.log("用户服务认证成功")
          // token 存入缓存
          // wx.setStorageSync('token', token);
        } 
      }
      else if(data.event == this.USERINFO){
        console.log("获取用户信息")
        let userInfo = data.data
        console.log(userInfo)
        wx.setStorageSync('userInfo', userInfo);
      }
     
    },

    _onError(err) {
        console.log(this.host + "，连接发生异常,游戏即将结束！");
        console.log(err)
    },
    
    send (msg) {
      console.log("与服务器发送消息~")
      console.log(msg)
    },


    /**
     * 心跳检测
     */
    heatCall(){
      var that = this
      // 重置定时器
      that.resetTimer()
      this.heartBeatTimer = setTimeout(()  => {  
          if (this.ws && this.ws.readyState === WebSocket.OPEN){
              console.log("send：heartBeat");
              this.ws.send(JSON.stringify(this.heartEvent));

              // 发送超过20秒未响应就自动关闭socket
              that.delayWaitTime = setTimeout(() => {
                that.resetConnect()
              }, 5000)
              console.log("delayWaitTime："+ that.delayWaitTime)
          }
      }, this.times)
    },

  /**
   * 尝试重连3次
   */ 
  resetConnect(){
    if (this.ws && this.ws.readyState == WebSocket.OPEN){
      this.heatCall()
    }else {
        this.ws.close();
        if (this.resetCount < 3){
            this.resetCount++;
            // 断线重连
            console.log("*******************reconncet**********************");
            console.log("第"+this.resetCount+"次重连！");
            this.connect();
            //10秒时间，如果没有连接成功就关闭连接，并且再也不重连
            this.lastReconnectTime = setTimeout(() => {
                if (!this.ws || this.ws.readyState != WebSocket.OPEN){
                  this.ws.close();
                }
            }, 10000);
            console.log("lastReconnectTime:"+this.lastReconnectTime)
        }else{
          console.log("服务器重连已达3次，游戏已关闭！")
        }
    }
  },

  /**
   * 重置定时器
   */
  resetTimer(){
    this.heartBeatTimer && clearTimeout(this.heartBeatTimer);
    this.delayWaitTime && clearTimeout(this.delayWaitTime);
    this.resetCount=0;
  },


  // *********************** API  ***********************
  // 登录
  sendLogin(code){
    console.log("登录中···")
    let param = {
      event: this.WXLOGIN,
      data: {code:code}
    }
    this.ws.send(JSON.stringify(param));
  },

  // 服务端进行登录获取请求token
	sysAuthorize(openid) {
    let param = {
      event: this.SYSLOGIN,
      data: {
        thirdId: openid,
        channel: 'wechatGame'
      }
    }
    this.ws.send(JSON.stringify(param));
  }




};  

module.exports = websocket;
